import { notification, message } from 'ant-design-vue'
import axios from 'axios'
let baseUrl = ''
let timeout = 30 * 1000
let hasNotification = false
if (process.env.NODE_ENV !== 'development') {
    baseUrl = './'
    timeout = 60 * 1000
}

const service = axios.create({
    timeout: timeout,
})

service.interceptors.request.use(config => {
    config.url = baseUrl + config.url
    let token = localStorage.getItem('token')
    // if (config.data) {
    //     for (let key in config.data) {
    //         if ((config.data[key] ?? {}) !== config.data[key]) {
    //             delete config.data[key]
    //         }
    //     }
    // }
    // if (config.params) {
    //     for (let key in config.params) {
    //         if ((config.params[key] ?? {}) !== config.params[key]) {
    //             delete config.params[key]
    //         }
    //     }
    // }
    if (!config.headers.self) {
        config.headers = {
            Authorization: token,
            // 'Content-Type': 'application/json',
            'Content-Type': 'application/x-www-form-urlencoded',
        }
        if (['post', 'put'].some(n => config.method && n == config.method.toLowerCase())) {
            config.headers['Content-Type'] = 'application/json; charset=UTF-8'
        }
    }
    return config
})

service.interceptors.response.use(
    response => {
        if (response.status === 200) {
            if ((!response.data && response.data !== false) || (response.data.code && response.data.code != 200)) {
                return Promise.reject(response)
            }
            return response.data
        } else {
            return Promise.reject(response)
        }
    },
    error => {
        console.log(error)
        if (error.response) {
            return Promise.reject(error.response) //未超时，能拿到错误码
        } else {
            return Promise.reject(error) //超时，拿不到错误码
        }
    },
)
const createNotification = function () {
    if (!hasNotification) {
        notification.open({
            message: '系统通知',
            description: '登陆状态过期，请重新登陆',
            onClose() {
                hasNotification = false
            },
        })
        hasNotification = true
    }
}
const notification401 = msg => {
    createNotification(msg) // msg
    setTimeout(() => {
        router.push('/login')
    })
}
function whenErr(url, resolve, reject, error) {
    if (error instanceof Error) {
        message.error(error.message)
        return reject(error.message)
    } else {
        const { status, data = {} } = error
        const isProduction = process.env.NODE_ENV === 'production'
        const code = data.code ? data.code : status
        if (code) {
            switch (code) {
                case 401:
                case '401':
                    notification401(data.message)
                    break
                case 404:
                    isProduction && message.error('404未找到')
                    !isProduction && message.error(`/${url} --> 404 not found`)
                    break
                default:
                    message.error(`${data.message || '服务器响应出错'}`)
                    break
            }
        } else {
            message.error(`${data.message || '服务器响应出错'}`)
        }
        return reject(data)
    }
}

export function get(url, data, responseType = '') {
    return new Promise((resolve, reject) => {
        service({
            method: 'get',
            url: url,
            params: data || '',
            responseType,
        })
            .then(res => {
                resolve(res)
            })
            .catch(e => {
                whenErr(url, resolve, reject, e)
            })
    })
}

export function put(url, data) {
    return new Promise((resolve, reject) => {
        service({
            method: 'put',
            url: url,
            data,
        })
            .then(res => {
                resolve(res)
            })
            .catch(e => {
                whenErr(url, resolve, reject, e)
            })
    })
}

export function del(url, data, isJson = false) {
    return new Promise((resolve, reject) => {
        service({
            method: 'delete',
            url: url,
            params: isJson ? '' : data || '',
            data: isJson ? data : null,
        })
            .then(res => {
                resolve(res)
            })
            .catch(e => {
                whenErr(url, resolve, reject, e)
            })
    })
}

export function post(url, data, headers = {}) {
    let arr = Object.keys(headers)
    if (arr.length > 0) {
        headers.self = true
    }
    return new Promise((resolve, reject) => {
        service({
            method: 'post',
            url: url,
            data: data,
            headers,
        })
            .then(res => {
                resolve(res)
            })
            .catch(e => {
                whenErr(url, resolve, reject, e)
            })
    })
}

export default {
    baseUrl,
    post,
    get,
    put,
    del,
    notification401,
}
